
package com.catsic.zcjc.web.controller;

import java.io.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.catsic.base.BaseInfo;
import com.catsic.base.annotation.Log;
import com.catsic.base.controller.BaseController;
import com.catsic.zcjc.condition.EquipDataCondition;
import com.catsic.zcjc.convert.ZcjcConverts;
import com.catsic.zcjc.entity.EquipData;
import com.catsic.zcjc.entity.EquipDataMark;
import com.catsic.zcjc.entity.EquipFileData;
import com.catsic.zcjc.entity.MarkLabel;
import com.catsic.zcjc.enums.EquipDataTag;
import com.catsic.zcjc.form.EquipDataForm;
import com.catsic.zcjc.form.MarkLabelForm;
import com.catsic.zcjc.form.StationCountForm;
import com.catsic.zcjc.service.EquipDataMarkService;
import com.catsic.zcjc.service.EquipDataService;
import com.catsic.zcjc.service.EquipFileDataService;
import com.catsic.zcjc.service.MarkLabelService;
import com.catsic.zcjc.util.DateUtils;

@Controller
@RequestMapping("/equipData")
public class EquipDataController extends BaseController {

	@Autowired
	private EquipDataService equipDataService;

	@Autowired
	private EquipFileDataService equipFileDataService;

	@Autowired
	private EquipDataMarkService equipDataMarkService;
	
	@Autowired
	private MarkLabelService markLabelService;

	/**
	 * 查询设备数据
	 * 
	 * @author xietiebing
	 * @param condition
	 * @return
	 */
	@RequestMapping(value = "/query", method = RequestMethod.GET)
	@ResponseBody
	public Map<String, Object> query(EquipDataCondition condition, Pageable pageable) {
		Page<EquipDataForm> page = equipDataService.findAll(condition, pageable);
		
		if("search".equalsIgnoreCase(condition.getComeFrom())){
			//加载标签
			List<EquipDataForm> list = page.getContent();
			if(CollectionUtils.isNotEmpty(list)){
				for(EquipDataForm form : list){
					List<EquipDataMark> markList = equipDataMarkService.findByDataIdAndCreate(form.getId(), getCurrentUser().getUserId());
					
					String labelName = "";
					if(CollectionUtils.isNotEmpty(markList)){
						for(EquipDataMark mark : markList){
							if(mark.getMarkLabel()!=null){
								labelName = labelName +mark.getMarkLabel().getLabel()+" ";
							}
						}
						
						form.setLabelName(labelName.trim());
					}
				}
			}
		}
		
		Map<String, Object> map = new HashMap<String, Object>();
		map.put(CONTENT, page);
		map.put(RESULT, RESULT_SUCCESS);
		return map;
	}

	/**
	 * detail:已读
	 * 
	 * @author xietiebing
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/read", method = RequestMethod.GET)
	@ResponseBody
	public Map<String, Object> read(String id) {
		EquipData data = equipDataService.findById(id);
		data.setTag(EquipDataTag.READ.getIndex());
		equipDataService.update(data);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put(RESULT, RESULT_SUCCESS);
		return map;
	}

	/**
	 * all:详情
	 * 
	 * @author xietiebing
	 * @return
	 */
	@RequestMapping(value = "/getMarkData.json", method = RequestMethod.GET)
	@ResponseBody
	public List<MarkLabelForm> all(String dataId) {
		BaseInfo baseInfo = getCurrentUser();
		String createId = baseInfo.getUserId();
		List<EquipDataMark> dataMarks = equipDataMarkService.findByDataIdAndCreate(dataId, createId);
		List<String> selectedMarkIds = new ArrayList<>();
		if (!dataMarks.isEmpty()) {
			for (EquipDataMark dataMark : dataMarks) {
				selectedMarkIds.add(dataMark.getMarkLabel().getId());
			}
		}
		List<MarkLabelForm> result = new ArrayList<>();
		List<MarkLabel> marks = markLabelService.findAll();
		for (MarkLabel markLabel : marks) {
			String id = markLabel.getId();
			MarkLabelForm form = ZcjcConverts.convert(markLabel);
			if (selectedMarkIds.contains(id)) {
				form.setSelected(true);
			}
			result.add(form);
		}
		return result;
	}

	/**
	 * detail:标记
	 * 
	 * @author xietiebing
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/updateMark")
	@ResponseBody
	@Log(module = "检测记录", operation = "标记数据")
	public Map<String, Object> updateMark(String id, @RequestParam(value = "marks[]") String[] marks) {
		BaseInfo user = getCurrentUser();
		
		equipDataMarkService.updateSaveMark(id, marks, user);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put(RESULT, RESULT_SUCCESS);
		return map;
	}

	/**
	 * detail:详情
	 * 
	 * @author xietiebing
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/detail", method = RequestMethod.GET)
	@ResponseBody
	public Map<String, Object> detail(String id) {
		EquipDataForm form = equipDataService.findEquipDataById(id);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put(CONTENT, form);
		map.put(RESULT, RESULT_SUCCESS);
		return map;
	}

	/**
	 * now:实时数据
	 * 
	 * @author xietiebing
	 * @param condition
	 * @return
	 */
	@RequestMapping(value = "/now", method = RequestMethod.GET)
	@ResponseBody
	public Map<String, Object> now(EquipDataCondition condition) {

		Date now = new Date();
		Date beginDate = DateUtils.getBeginningOfADay(now);

		condition.setBeginDate(DateUtils.format(beginDate, "yyyy-MM-dd HH:mm:ss"));
		condition.setEndDate(DateUtils.format(now, "yyyy-MM-dd HH:mm:ss"));

		EquipDataForm form = equipDataService.findNowData(condition);
		form.setCountTime(now);

		Map<String, Object> map = new HashMap<String, Object>();
		map.put(CONTENT, form);
		map.put(RESULT, RESULT_SUCCESS);
		return map;
	}

	/**
	 * count:热力图统计
	 * 
	 * @author xietiebing
	 * @param type
	 * @return
	 */
	@RequestMapping(value = "/count")
	@ResponseBody
	public Map<String, Object> count(String type) {
		EquipDataCondition condition = new EquipDataCondition();
		/*
		 * Date now = new Date(); Date beginDate =
		 * DateUtils.getBeginningOfADay(now);
		 * 
		 * condition.setBeginDate(DateUtils.format(beginDate,
		 * "yyyy-MM-dd HH:mm:ss")); condition.setEndDate(DateUtils.format(now,
		 * "yyyy-MM-dd HH:mm:ss"));
		 */

		List<StationCountForm> form = equipDataService.findByCount(type, condition);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put(CONTENT, form);
		map.put(RESULT, RESULT_SUCCESS);
		return map;
	}

	@RequestMapping(value = "/showFile", method = RequestMethod.GET)
	public void showFile(@RequestParam(value = "dataId") String dataId, @RequestParam(value = "type") int type,
			HttpServletRequest request, HttpServletResponse response) {
		response.setHeader("Cache-Control", "no-cache");
		response.setHeader("Cache-Control", "no-store");
		response.setHeader("Pragma", "no-cache");
		response.setDateHeader("Expires", 0);
		EquipFileData dataFile = equipFileDataService.findByDataIdAndType(dataId, type);
		if (dataFile != null) {
			File file = new File(dataFile.getFilePath() + dataFile.getFileName());
			response.setCharacterEncoding("utf-8");
			response.setContentType("multipart/form-data");
			response.setHeader("Content-Disposition", "attachment;fileName=\"" + dataFile.getFileName() + "\"");
			try {
				InputStream inputStream = new FileInputStream(file);
				OutputStream os = response.getOutputStream();
				byte[] b = new byte[1024];
				int length;
				while ((length = inputStream.read(b)) > 0) {
					os.write(b, 0, length);
				}
				inputStream.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			response.setHeader("content-type", "text/html;charset=UTF-8");
			try {
				String data = "该记录无附件！";
				OutputStream outputStream = response.getOutputStream();
				byte[] dataByteArr = data.getBytes("UTF-8");
				outputStream.write(dataByteArr);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

    @ResponseBody
    @RequestMapping(value = "/headPic.img", method = RequestMethod.GET,
            produces = MediaType.IMAGE_PNG_VALUE)
    public byte[] avatar(@RequestParam(value = "dataId") String dataId, @RequestParam(value = "type") int type,
                         HttpServletRequest request, HttpServletResponse response) {
        byte[] icon = null;
        try {
            EquipFileData dataFile = equipFileDataService.findByDataIdAndType(dataId, type);
            if (dataFile != null) {
                File file = new File(dataFile.getFilePath() + dataFile.getFileName());
                InputStream in = new FileInputStream(file);
                icon = IOUtils.toByteArray(in);
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return icon;
    }
}
